package com.wy.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Controller
@RequestMapping("fileStream")
@CrossOrigin("*")
public class FileStreamController {
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(HttpServletRequest request) {
        try (InputStream inputStream = request.getInputStream()) {
            // 保存文件到本地
            Path filePath = Paths.get("C:\\Users\\Administrator\\Desktop\\ffff\\1.jpg");
            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
            return ResponseEntity.ok("文件上传成功");
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败");
        }
    }
    @GetMapping("/download")
    public ResponseEntity<StreamingResponseBody> downloadFile(@RequestParam String fileName) {
        try {
            File file = new File("C:\\Users\\Administrator\\Desktop\\ffff\\1.jpg");
            if (file.exists()) {
                InputStream inputStream = new FileInputStream(file);

                StreamingResponseBody responseBody = outputStream -> {
                    int nRead;
                    byte[] data = new byte[1024];
                    while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                        outputStream.write(data, 0, nRead);
                    }
                    inputStream.close();
                };

                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                        .body(responseBody);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }

        } catch (FileNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }
}
